package com.soft.mainsite.component.beetl.tag.cms;

import com.soft.mainsite.common.utils.StrUtil;
import com.soft.mainsite.module.category.service.TCmsCategoryService;
import com.soft.mainsite.module.publishlog.service.PublishLogService;
import com.soft.mainsite.module.web.cms.service.CategoryService;
import com.soft.mainsite.module.web.cms.service.SiteService;
import com.soft.mainsite.common.exception.CmsException;
import com.soft.mainsite.common.utils.CmsUtil;
import com.soft.mainsite.common.utils.Pojo2MapUtil;
import com.soft.mainsite.mybatis.model.TCmsCategory;
import com.soft.mainsite.mybatis.model.TCmsSite;
import lombok.extern.slf4j.Slf4j;
import org.beetl.core.GeneralVarTagBinding;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * Description:栏目列表标签
 *
 * @author Jin
 * @create 2017-05-26
 **/
@Slf4j
@Service
@Scope("prototype")
public class CategoryListTag extends GeneralVarTagBinding {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private TCmsCategoryService tCmsCategoryService;
    @Autowired
    private SiteService siteService;

    @Autowired
    private PublishLogService publishLogService;

    @Value("${system.http.protocol}")
    private String httpProtocol;

    @Value("${system.http.host}")
    private String httpHost;

    @Value("${system.site.prefix}")
    private String sitePrefix;

    @Value("${system.site.subfix}")
    private String siteSubfix;


    @Override
    public void render() {
        Integer siteId = (this.getAttributeValue("siteId") instanceof String) ? Integer.parseInt((String) this.getAttributeValue("siteId")) : (Integer) this.getAttributeValue("siteId");
        Long categoryId = (this.getAttributeValue("categoryId") instanceof String) ? Long.parseLong((String) this.getAttributeValue("categoryId")) : (Long) this.getAttributeValue("categoryId");
        Integer isNav = Integer.parseInt((String) this.getAttributeValue("isNav"));
        try {
            this.wrapRender(siteId, categoryId, (isNav.intValue() == 1 ? true : false));
        } catch (Exception e) {
            log.error("栏目列表标签渲染失败,栏目id：{}", categoryId, e);
            publishLogService.save(siteId, categoryId, "", "栏目列表标签渲染失败,栏目id:" + categoryId);
            throw new CmsException("栏目列表标签渲染失败，" + "栏目id:" + categoryId);
        }

    }

    /**
     * 修改了获取栏目的tCmsCategoryService.findCategoryListByPidAndIsNav
     *
     * @param siteId
     * @param categoryId
     * @param isNav
     * @throws Exception
     */
    private void wrapRender(Integer siteId, Long categoryId, boolean isNav) throws Exception {
        TCmsSite site = siteService.findById(siteId);
        if (CmsUtil.isNullOrEmpty(site)) {
            throw new CmsException("站点不存在[siteId:" + siteId + "]");
        }
        List<TCmsCategory> cats = tCmsCategoryService.findCategoryListByPidAndIsNav(categoryId, siteId, isNav == true ? 1 : 0);
        int i = 1;
        if (CmsUtil.isNullOrEmpty(cats)) {
            TCmsCategory category = categoryService.findById(categoryId);
            if (CmsUtil.isNullOrEmpty(category)) {
                throw new CmsException("没有查询到数据！[siteId:" + siteId + ",categoryId:" + categoryId + "]");
            }
            cats = tCmsCategoryService.findCategoryListByPidAndIsNav(category.getParentId(), siteId, isNav == true ? 1 : 0);
        }
        HttpServletRequest request = (HttpServletRequest) ctx.getGlobal("request");
        String staticHtmlPath = ctx.getGlobal("staticHtmlPath") == null ? "" : (String) ctx.getGlobal("staticHtmlPath");
        for (TCmsCategory category : cats) {
            if (StrUtil.isBlank(category.getUrl())) {
                category.setUrl(request.getContextPath() + staticHtmlPath + "/" + site.getSiteKey() + "/" + category.getAlias() + siteSubfix);
            }
            Map result = Pojo2MapUtil.toMap(category);
            result.put("prototype", category);
            result.put("index", i);
            this.binds(result);
            this.doBodyRender();
            i++;
        }
    }

}
